package com.ms.education.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ms.education.cms.entity.Banner;
import com.ms.education.cms.entity.BannerGroup;
import com.ms.education.cms.entity.vo.BannerGroupVo;
import com.ms.education.cms.mapper.BannerGroupMapper;
import com.ms.education.cms.service.BannerGroupService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ms.education.cms.service.BannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ms
 * @since 2023-01-21
 */
@Service
public class BannerGroupServiceImp extends ServiceImpl<BannerGroupMapper, BannerGroup> implements BannerGroupService {

    @Autowired
    private BannerService bannerService;

    @Override
    public List<BannerGroup> getBannerGroup(BannerGroupVo bannerGroupVo) {
        String title = bannerGroupVo.getTitle();
        Boolean isShow = bannerGroupVo.getIsShow();
        Date beginTime = bannerGroupVo.getBeginTime();
        Date endTime = bannerGroupVo.getEndTime();
        QueryWrapper<BannerGroup> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(title)) {
            wrapper.like("title", title);
        }
        if (!StringUtils.isEmpty(isShow)) {
            wrapper.eq("is_show", isShow);
        }
        if (!StringUtils.isEmpty(beginTime)) {
            wrapper.ge("gmt_create", beginTime);
        }
        if (!StringUtils.isEmpty(endTime)) {
            wrapper.le("gmt_create", endTime);
        }
        wrapper.orderByDesc("is_show").orderByDesc("gmt_modified");
        return this.list(wrapper);
    }

    @Override
    public void deleteBannerGroupsByIds(Integer[] bannerGroupsIds) {
        //先删除分组的banner
        UpdateWrapper<Banner> wrapper = new UpdateWrapper<>();
        wrapper.in("group_id", bannerGroupsIds);
        bannerService.remove(wrapper);

        //删除分组
        this.removeBatchByIds(Arrays.asList(bannerGroupsIds));

    }

    @Override
    @CacheEvict(value = "banners", allEntries = true)
    public void showGroup(Integer id) {
        //是当前在展示的分组不展示
        UpdateWrapper<BannerGroup> wrapper = new UpdateWrapper<>();
        wrapper.set("is_show", false).eq("is_show", true);
        this.update(wrapper);
        //展示当前分组
        wrapper = new UpdateWrapper<>();
        wrapper.set("is_show", true).eq("id", id);
        this.update(wrapper);
    }
}
